/**
 * ${table.comment!(table.entityName!'')} - API接口
 * 
 * 遵循Kexio开发规范：
 * - 统一的请求响应格式
 * - 标准的CRUD操作接口
 * - 支持分页查询和条件筛选
 * - 支持批量操作和导入导出
 * - 使用 request.download/upload 简化文件操作
 * - 提供 WithUI 封装函数供组件直接调用
 * 
 * 对应后端接口：/${table.moduleName}/${lowerEntity}
 * 
 * @author ${user.name!"系统"}
 * @since ${now?string('yyyy-MM-dd HH:mm:ss')}
 */
import request from '@/utils/request'
import { validateExcelFile } from '@/utils/request'
import type { ApiResponse, PageResponse } from '@/types/api'
import { ElMessage, ElMessageBox } from 'element-plus'

const base = '/<#if table.moduleName??>${table.moduleName}<#else>system</#if>/<#if lowerEntity??>${lowerEntity}<#else>entity</#if>'

// ==================== 基础 API ====================

export const ${lowerEntity}Api = {
  /**
   * 分页查询${table.comment!(table.entityName!'')}
   */
  list${table.entityName}: (params: any): Promise<ApiResponse<PageResponse<any>>> => {
    return request.get(`${'$'}{base}`, { params })
  },

  /**
   * 查询${table.comment!(table.entityName!'')}详情
   */
  get${table.entityName}: (id: string | number): Promise<ApiResponse<any>> => {
    return request.get(`${'$'}{base}/${'$'}{id}`)
  },

  /**
   * 新增${table.comment!(table.entityName!'')}
   */
  create${table.entityName}: (data: any): Promise<ApiResponse<any>> => {
    return request.post(base, data)
  },

  /**
   * 更新${table.comment!(table.entityName!'')}
   */
  update${table.entityName}: (id: string | number, data: any): Promise<ApiResponse<any>> => {
    return request.put(`${'$'}{base}/${'$'}{id}`, data)
  },

  /**
   * 删除${table.comment!(table.entityName!'')}
   */
  delete${table.entityName}: (id: string | number): Promise<ApiResponse<void>> => {
    return request.delete(`${'$'}{base}/${'$'}{id}`)
  },

  /**
   * 批量删除${table.comment!(table.entityName!'')}
   */
  batchDelete${table.entityName}: (ids: (string | number)[]): Promise<ApiResponse<void>> => {
    return request.delete(`${'$'}{base}/batch`, { data: ids })
  },

<#if table.templateType?has_content && table.templateType == 'multi'>
  /**
   * 创建${table.comment!(table.entityName!'')}（含关联关系）
   */
  create${table.entityName}WithRelations: (data: any): Promise<ApiResponse<any>> => {
    return request.post(`${'$'}{base}/with-relations`, data)
  },

  /**
   * 更新${table.comment!(table.entityName!'')}（含关联关系）
   */
  update${table.entityName}WithRelations: (id: string | number, data: any): Promise<ApiResponse<any>> => {
    return request.put(`${'$'}{base}/${'$'}{id}/with-relations`, data)
  },

</#if>
  /**
   * 导出${table.comment!(table.entityName!'')}
   */
  export${table.entityName}: async (params: any): Promise<void> => {
    return request.download({
      url: `${'$'}{base}/export`,
      params,
      filename: `${table.comment!table.entityName}列表_${'$'}{new Date().toISOString().slice(0, 10)}.xlsx`
    })
  },

  /**
   * 导入${table.comment!(table.entityName!'')}
   */
  import${table.entityName}: (file: File, updateSupport: boolean = false): Promise<ApiResponse<{
    total: number
    successCount: number
    failureCount: number
    errorMessages: string[]
  }>> => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('updateSupport', String(updateSupport))
    
    return request.upload({
      url: `${'$'}{base}/import`,
      data: formData,
      showMessage: false
    })
  },

  /**
   * 下载导入模板
   */
  downloadImportTemplate: async (): Promise<void> => {
    return request.download({
      url: `${'$'}{base}/template`,
      filename: '${table.comment!table.entityName}导入模板.xlsx'
    })
  }
}

// ==================== 高级封装函数（组件直接调用） ====================

/**
 * 导出${table.comment!(table.entityName!'')}（封装了所有业务逻辑）
 * @example await export${table.entityName}WithUI(queryParams)
 */
export const export${table.entityName}WithUI = async (params: any): Promise<void> => {
  try {
    await ${lowerEntity}Api.export${table.entityName}(params)
  } catch (error) {
    console.error('导出失败:', error)
  }
}

/**
 * 导入${table.comment!(table.entityName!'')}（封装了验证、上传、结果显示）
 * @example await import${table.entityName}WithUI(file, true, () => getList())
 */
export const import${table.entityName}WithUI = async (
  file: File | null,
  updateSupport: boolean,
  onSuccess?: () => void
): Promise<void> => {
  if (!file) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  // 验证文件
  const validation = validateExcelFile(file)
  if (!validation.valid) {
    ElMessage.error(validation.message!)
    return
  }

  try {
    ElMessage.info('正在导入${table.comment!table.entityName}数据...')
    
    const response = await ${lowerEntity}Api.import${table.entityName}(file, updateSupport)
    const result = response.data
    
    const successMsg = `导入完成！总计: ${'$'}{result.total}, 成功: ${'$'}{result.successCount}, 失败: ${'$'}{result.failureCount}`
    
    if (result.failureCount > 0 && result.errorMessages.length > 0) {
      ElMessageBox.alert(
        `${'$'}{successMsg}\n\n失败详情：\n${'$'}{result.errorMessages.slice(0, 10).join('\n')}${'$'}{result.errorMessages.length > 10 ? '\n...' : ''}`,
        '导入结果',
        { confirmButtonText: '确定', type: 'warning' }
      )
    } else {
      ElMessage.success(successMsg)
    }
    
    if (onSuccess) {
      onSuccess()
    }
  } catch (error) {
    console.error('导入失败:', error)
  }
}

/**
 * 下载导入模板
 * @example await download${table.entityName}TemplateWithUI()
 */
export const download${table.entityName}TemplateWithUI = async (): Promise<void> => {
  try {
    await ${lowerEntity}Api.downloadImportTemplate()
  } catch (error) {
    console.error('下载模板失败:', error)
  }
}

// ==================== 默认导出 ====================

export default ${lowerEntity}Api
